<template>
  <el-dialog
    v-model="visible"
    :before-close="close"
    :title="!isShowProd
      ? $t('product.select')
      : $t('product.viewProduct')
    "
    :close-on-click-modal="false"
    class="component-distribution-prod-add-or-update"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{
            $t("order.query")
          }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{
            $t("shop.resetMap")
          }}
        </div>
      </el-form-item>
    </el-form>
    <div class="main-container distribution-prod-add-or-update">
      <div class="table-con prods-select-body">
        <el-table
          ref="prodTable"
          v-loading="dataListLoading"
          :data="dataList"
          :header-cell-style="{ height: '42px', background: '#F6F7FA', color: '#666666', 'font-weight': '500' }"
          :cell-style="{ height: '64px', padding: '8px 0', color: '#000' }"
          style="width: 100%;"
          height="420"
        >
          <!-- <el-table-column v-if="!isShowProd"
                          type="selection"
                          header-align="center"
                          align="center"
                          width="50">
          </el-table-column>-->
          <el-table-column
            width="50"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-radio
                  v-model="prodId"
                  :label="scope.row.prodId"
                  @change="getSelectProdRow(scope.$index, scope.row)"
                >
                  &nbsp;
                </el-radio>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="prodName"
            align="left"
            :label="$t('product.prodName')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.prodName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('product.pic')"
          >
            <template #default="scope">
              <prod-pic
                height="60px"
                width="60px"
                :pic="scope.row.pic"
              />
            </template>
          </el-table-column>
          <!-- 销售价(元) -->
          <el-table-column
            align="center"
            prop="price"
            :label="$t('product.sellingPrice')"
          />
        </el-table>
      </div>
    </div>
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
    <template #footer>
      <span>
        <div
          :class="[dataListSelections.length <= 0 ? 'disabled-btn' : '', 'default-btn primary-btn']"
          @click="selectProd(dataListSelections.length <= 0)"
        >{{ $t("crud.filter.submitBtn") }}</div>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
const emit = defineEmits(['refreshDiscountProds'])
const props = defineProps({
  isDistribution: {
    default: false,
    type: Boolean
  }
})

const Data = reactive({
  visible: false,
  dataForm: {
    product: ''
  },
  isShowProd: 0,
  allData: [],
  prodId: 0,
  discountProds: [],
  discountId: 0,
  prodName: '',
  shopCategoryId: null,
  dataList: [],
  pageIndex: 1,
  pageSize: 10,
  totalPage: 0,
  dataListLoading: false,
  dataListSelections: [],
  addOrUpdateVisible: false,
  categoryList: [],
  selectedCategory: [],
  categoryTreeProps: {
    value: 'categoryId',
    label: $t('language') === 'English' ? 'categoryNameEn' : 'categoryName'
  }
})

const { visible, dataForm, isShowProd, prodId, prodName, dataList, pageIndex, pageSize, totalPage, dataListLoading, dataListSelections, categoryList, selectedCategory, categoryTreeProps } = toRefs(Data)

// 获取数据列表
const init = (id, discountProds) => {
  Data.prodId = 0
  Data.discountProds = discountProds
  Data.discountId = id
  Data.visible = true
  Data.dataListLoading = true
  if (discountProds) {
    Data.discountProds.forEach(row => {
      Data.dataListSelections.push(row)
    })
  }
  getDataList()
  getCategoryList()
}

const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      status: 1
    })
  }).then(({ data }) => {
    Data.categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}

const showProd = (id, val) => {
  Data.isShowProd = val
  Data.visible = true
  http({
    url: http.adornUrl(`/admin/discountProd/info/${id}`),
    method: 'get',
    params: http.adornParams({
      page: Data.pageIndex,
      limit: Data.pageSize,
      discountId: id
    })
  }).then(({ data }) => {
    Data.dataList = data
  })
}

const prodTableRef = ref()
const getDataList = () => {
  http({
    url: http.adornUrl('/distribution/distributionProd/canDistributionProdPage'),
    method: 'get',
    params: http.adornParams({
      current: Data.pageIndex,
      size: Data.pageSize,
      prodName: Data.prodName ? Data.prodName : null,
      shopCategoryId: Data.shopCategoryId ? Data.shopCategoryId : null,
      status: 1,
      isDistribution: props.isDistribution ? 1 : 0,
      isActive: 1 // 过滤掉活动商品
    })
  }).then(({ data }) => {
    Data.dataList = data.records
    Data.totalPage = data.total
    Data.dataListLoading = false
    nextTick(() => {
      if (Data.discountProds) {
        Data.discountProds.forEach(row => {
          const index = Data.dataList.findIndex(
            prodItem => prodItem.prodId === row.prodId
          )
          prodTableRef.value.toggleRowSelection(Data.dataList[index])
        })
      }
    })
  })
}

// 每页数
const sizeChangeHandle = (val) => {
  Data.pageSize = val
  Data.pageIndex = 1
  getDataList()
}

// 当前页
const currentChangeHandle = (val) => {
  Data.pageIndex = val
  getDataList()
}

/**
     * 获取分类id
     */
const handleChange = (val) => {
  Data.shopCategoryId = val[val.length - 1]
}

/**
     * 根据条件搜索商品
     */
const searchProd = () => {
  Data.pageIndex = 1
  if (props.isDistribution) {
    getDataList()
  } else {
    init(Data.discountId, Data.discountProds)
  }
}

/**
     * 清空搜索条件
     */
const clean = () => {
  Data.prodName = ''
  Data.shopCategoryId = null
  Data.selectedCategory = idList(Data.categoryList, Data.shopCategoryId, 'categoryId', 'children').reverse()
}

const close = () => {
  Data.prodName = ''
  Data.shopCategoryId = null
  Data.visible = false
}

// 选择产品
const selectProd = (status) => {
  if (status) {
    return
  }
  const prods = []
  Data.dataListSelections.forEach(item => {
    const prodIndex = prods.findIndex(prod => prod.prodId === item.prodId)
    if (prodIndex === -1) {
      prods.push({
        discountProdId: 0,
        prodId: item.prodId,
        prodName: item.prodName,
        pic: item.pic
      })
    }
  })
  emit('refreshDiscountProds', prods)
  Data.dataListSelections = []
  Data.visible = false
}

// 获取当选的行
const getSelectProdRow = (index, row) => {
  Data.dataListSelections = []
  Data.dataListSelections.push(row)
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.component-distribution-prod-add-or-update {
  .distribution-prod-add-or-update {
    padding: 0;
    max-height: 480px;
    overflow: auto;

    .table-con {
      padding-bottom: 20px;
    }

    ::v-deep(.el-table__body-wrapper::-webkit-scrollbar) {
      width: 6px;
      height: 439px;
      background: #F7F8FA;
      opacity: 1;
      border-radius: 4px;
    }

    // 滚动条的滑块
    ::v-deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
      width: 6px;
      height: 150px;
      background: #E9ECF3;
      opacity: 1;
      border-radius: 4px;
    }
  }
}
</style>
